from urllib import urlencode

from httplib2 import Http
from scrapy.conf import settings


h = Http()
SERVER = settings['DJANGO_SERVER']


class DragonPipeline(object):
    def process_item(self, domain, item):
        type = item.__class__.__name__
        data = {}
        if type == 'Topic':
            data['type'] = 'thread'
            data['id'] = item['id']
            data['url'] = item['url']
            data['title'] = item['title']
        elif type == 'Message':
            data = {
                'type': 'post',
                'id': item['id'],
                'thread': item['topic'],
                'author': item['author'],
                'datetime': item['datetime'],
                'text': item['text']
            }
        data = dict([k, v.encode('utf-8')] for k, v in data.items())
        body = urlencode(data)
        api_url = '%s/api/update' % SERVER
        response, content =  h.request(api_url, method='POST', body=body)
        if response.status != 200:
            raise Exception("Error while submitting request: %s" % body)
        return item
